package com.demo.interview.abcabc;

/**
 * 现在两个线程，可以操作初始值为0的变量，实现一个线程对该变量+1，一个线程从对该变量-1，实现交替，来10轮，变量初始值为0
 * @author shenguangyang
 */
public class ProdConsumer_sync {
    private int number = 0;

    public synchronized void increment() throws InterruptedException {
        while (number != 0) {
            this.wait();
        }
        number++;
        System.out.println(Thread.currentThread().getName() + "\t" + number);
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while (number == 0){
            this.wait();
        }
        number--;
        System.out.println(Thread.currentThread().getName() + "\t" + number);
        this.notifyAll();
    }

    public static void main(String[] args) {
        ProdConsumer_sync prodConsumerSync = new ProdConsumer_sync();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.increment();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    prodConsumerSync.decrement();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();
    }
}
